#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

export PATH=$TOP_DIR/cross/bin:$PATH

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -f bzip2-1.0.6.tar.gz ] ; then
		wget http://bzip.org/1.0.6/bzip2-1.0.6.tar.gz
	fi
	cd ..
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	rm -rf $BIN_DIR/bzip2
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_bzip2
	tar xzf $SRC_DIR/bzip2-1.0.6.tar.gz
	mv bzip2-1.0.6 bd_bzip2
	cd bd_bzip2
	patch -p0 < $TOP_DIR/patch/bzip2-w64.patch
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		CROSS=i686-w64-mingw32
	else
		CROSS=x86_64-w64-mingw32
	fi
	make CC=$CROSS-gcc AR=$CROSS-ar RANLIB=$CROSS-ranlib -f Makefile
	$CROSS-gcc -shared -Wl,--out-implib,libbz2dll.a -o bz2dll.dll \
		blocksort.o huffman.o crctable.o randtable.o compress.o decompress.o bzlib.o
	
	mkdir -p $BIN_DIR/bzip2/bin
	cp bzip2 $BIN_DIR/bzip2/bin/bzip2.exe
	cp bz2dll.dll $BIN_DIR/bzip2/bin/
	mkdir -p $BIN_DIR/bzip2/include
	cp bzlib.h $BIN_DIR/bzip2/include/
	mkdir -p $BIN_DIR/bzip2/lib
	cp libbz2.a libbz2dll.a $BIN_DIR/bzip2/lib/

	cd ..
	cd ..
fi

